package com.huawei.chengdu.meetingdemo.view.dialogs;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;

import com.huawei.chengdu.meetingdemo.consts.ObserverConts;
import com.huawei.chengdu.meetingdemo.consts.ConfConst;

import java.util.Timer;
import java.util.TimerTask;

import com.huawei.chengdu.meetingdemo.R;
import com.huawei.chengdu.meetingdemo.presenter.ConfSdkPresenter;
import com.huawei.chengdu.meetingdemo.view.IViewDataObserver;
import com.huawei.chengdu.meetingdemo.presenter.MeetingManager;
import com.huawei.chengdu.meetingdemo.view.MeetingControlView;

public class VoiceSelectWindow extends FloatWindowBase
        implements View.OnClickListener, SeekBar.OnSeekBarChangeListener, IViewDataObserver {

    /**
     * 扬声器是否静音字符串
     */
    public static final String SPEAKER_STATUS_NOTIFY_ISMUTE = "SPEAKER_STATUS_NOTIFY_ISMUTE";

    /**
     * 扬声器音量字符串
     */
    public static final String SPEAKER_STATUS_NOTIFY_VOLUME = "SPEAKER_STATUS_NOTIFY_VOLUME";
    /**
     * check status
     */
    public static boolean isMove = false;

    private static final String TAG = "VoiceSelectWindow";

    // 音量条窗口的宽度固定值，请误改动
    private static final int VOICE_SELECT_WINDOW_WIDTH = 144;

    // 音量条窗口的高度固定值，请误改动
    private static final int VOICE_SELECT_WINDOW_HEIGHT = 640;

    LinearLayout llRoot;

    private SeekBar soundSB;

    private ImageView soundIV;

    private Timer hideTimer = null;

    private long time = 5000;

    private TimerTask hideTask = null;

    // 弹框X坐标，初始化为0
    private int volumeMenuX = 0;

    // 弹框Y坐标，距离会控栏的距离 会控栏上边距有15px的阴影
    private int volumeMenuY = 16;

    private int positionX;

    private boolean isQuite = true;

    private int volume;

    private MeetingControlView meetingControlView;

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            release();
        }
    };

    public VoiceSelectWindow(Context context, int positionX, MeetingControlView meetingControlView) {
        super(context);
        super.setWmTitleParams("VoiceSelectWindow"); // 设置窗口title的固定字段，请误改动
        // 下面的数字0和0表示X坐标和y坐标的值，固定字段请勿改动。
        super.setWmPositionParams(Gravity.BOTTOM | Gravity.START, 0, 0,
                VOICE_SELECT_WINDOW_WIDTH, VOICE_SELECT_WINDOW_HEIGHT);
        wmParams.flags = wmParams.flags | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        this.positionX = positionX;
        this.meetingControlView = meetingControlView;
        hideTimer = new Timer();
        init();
    }

    private void init() {
        llRoot = mRootView.findViewById(R.id.ll_root);
        soundSB = mRootView.findViewById(R.id.sound_seekbar);
        soundIV = mRootView.findViewById(R.id.sound_img);
        soundIV.setOnClickListener(this);
        isQuite = ConfSdkPresenter.isQuiet();

        volume = ConfSdkPresenter.getAudioVolume();
        Log.d(TAG, "volume:" + volume);
        soundSB.setProgress(volume);

        // 这个方法一定要放在volume初始化之后，因为它要用到volume的值。
        setSpeakerState();

        initSeekBarListener();
        initViewMove();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initViewMove() {
        mRootView.setOnTouchListener((View v, MotionEvent event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    Log.d(TAG, "ACTION_DOWN");
                    release();
                    isMove = true;
                    break;
                case MotionEvent.ACTION_MOVE:
                    break;
                case MotionEvent.ACTION_CANCEL:
                    Log.d(TAG, "ACTION_CANCEL");
                    isMove = false;
                    break;
                case MotionEvent.ACTION_UP:
                    Log.d(TAG, "ACTION UP");
                    isMove = false;
                    break;
                case MotionEvent.ACTION_OUTSIDE:
                    new Handler().postDelayed(runnable, 200);
                    break;
                default:
                    break;
            }
            return false;
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.voice_layout;
    }

    @Override
    protected String getChildName() {
        return TAG;
    }

    /**
     * Release widget
     */
    @Override
    public void release() {
        Log.d(TAG, "release");
        super.release();
        if (hideTask != null) {
            hideTask.cancel();
            hideTask = null;
        }
        unRegisterListenService();
    }

    /**
     * show the window
     */
    @Override
    public void showFloatWindow() {
        Log.i(TAG, "showFloatWindow()");

        // 父类的显示调用放在这里，顺序不要乱，需要先设置X再调用才正常
        super.showFloatWindow();

        registerListenerService();
        isQuite = ConfSdkPresenter.isQuiet();
        Log.d(TAG, "showFloatWindow isQuite:" + isQuite);
        volume = ConfSdkPresenter.getAudioVolume();
        Log.d(TAG, "showFloatWindow volume:" + volume);
        soundSB.setProgress(volume);
        setSpeakerState();
        meetingControlView.setSpeakerVolume(isQuite);

        if (hideTask != null) {
            hideTask.cancel();
            hideTask = null;
        }
        hideTask = new TimerTask() {
            @Override
            public void run() {
                release();
            }
        };
        hideTimer.schedule(hideTask, time);
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initSeekBarListener() {
        soundSB.setOnTouchListener((View view, MotionEvent event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    Log.d(TAG, "ACTION_DOWN");
                    isMove = true;
                    break;
                case MotionEvent.ACTION_MOVE:
                    break;
                case MotionEvent.ACTION_CANCEL:
                    Log.d(TAG, "ACTION_CANCEL");
                    isMove = false;
                    break;
                case MotionEvent.ACTION_UP:
                    Log.d(TAG, "ACTION UP");
                    isMove = false;
                    break;
                default:
                    break;
            }
            return false;
        });
        soundSB.setOnSeekBarChangeListener(this);
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        Log.i(TAG, "progress:" + progress + " fromUser:" + fromUser);
        if (hideTask != null) {
            hideTask.cancel();
            hideTask = null;
            hideTask = new TimerTask() {
                @Override
                public void run() {
                    release();
                }
            };
            hideTimer = new Timer();
            hideTimer.schedule(hideTask, time);
        }

        if (fromUser) {
            volume = progress;
            ConfSdkPresenter.setAudioVolume(progress);
            // 当音量条设置为0时，就静音
            if (progress == 0) {
                isQuite = true;
                ConfSdkPresenter.closeSpeaker();
            } else {
                isQuite = false;
                ConfSdkPresenter.openSpeaker();
            }
            setSpeakerState();
            meetingControlView.setSpeakerVolume(isQuite);
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }

    /**
     * 用于适配音量条的位置
     *
     * @param toX 音量条左边靠屏幕左边的距离
     * @param toY 音量条上边靠屏幕上边的距离
     */
    public void setVolumeMenuXY(int toX, int toY) {
        Log.d(TAG, "setVolumeMenuXY toX = " + toX + ", toY = " + toY);

        this.dlgWidth = (int) mContext.getResources().getDimension(R.dimen.def_dimens_144);
        wmParams.x = toX - dlgWidth / 2;
        wmParams.y = toY + ConfConst.BOTTOM_CONF_HEIGHT + volumeMenuY;
    }

    private void setSpeakerState() {
        Log.d(TAG, "volume:" + volume);

        // 音量一共有15个，平均分为3组，0-5显示第一个图标
        if (volume > 0 && volume <= 5) {
            Log.d(TAG, "soundIV.setBackground bar_speaker_on01");
            soundIV.setBackground(mContext.getDrawable(R.drawable.bar_speaker_on01_background));
        }

        // 音量一共有15个，平均分为3组，5-10显示第二个图标
        if (volume > 5 && volume <= 10) {
            Log.d(TAG, "soundIV.setBackground bar_speaker_on02");
            soundIV.setBackground(mContext.getDrawable(R.drawable.bar_speaker_on02_background));
        }

        // 音量一共有15个，平均分为3组，大于10的显示第三个图标
        if (volume > 10) {
            Log.d(TAG, "soundIV.setBackground bar_speaker_on03");
            soundIV.setBackground(mContext.getDrawable(R.drawable.bar_speaker_on03_background));
        }

        // 设置静音状态的放在最后，因为volume不为0时也可能是静音状态。
        if (isQuite || (volume == 0)) {
            Log.d(TAG, "soundIV.setBackground bar_speaker_off");
            soundIV.setBackground(mContext.getDrawable(R.drawable.bar_speaker_off_background));
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.sound_img) {
            Log.d(TAG, "click speaker -------> isQuite = " + isQuite);
            if (volume <= 0) {
                Log.d(TAG, "volume <= 0, so cannot change mute status");
                return;
            }

            int result = -1;
            if (isQuite) {
                result = ConfSdkPresenter.openSpeaker();
            } else {
                result = ConfSdkPresenter.closeSpeaker();
            }

            if (result == 0) {
                Log.d(TAG, "click speaker -------> Successed ");
                isQuite = !isQuite;
                setSpeakerState();
                meetingControlView.setSpeakerVolume(isQuite);
            } else {
                Log.d(TAG, "click speaker -------> Failed");
            }
        }
    }

    @Override
    public void viewDataChanged(int eventId, Object obj) {
        Log.i(TAG, "viewDataChanged");
        switch (eventId) {
            case ObserverConts.SPEAKER_STATUS_CHANGE_MSG:
                Log.i(TAG, "SPEAKER_STATUS_CHANGE_MSG");
                if (!(obj instanceof Bundle)) {
                    Log.i(TAG, "SPEAKER_STATUS_CHANGE_MSG !(obj instanceof Bundle)");
                    break;
                }
                Bundle bundle = (Bundle) obj;
                isQuite = bundle.getBoolean(SPEAKER_STATUS_NOTIFY_ISMUTE);
                Log.i(TAG, "viewDataChanged isQuite:" + isQuite);
                volume = bundle.getInt(SPEAKER_STATUS_NOTIFY_VOLUME);
                Log.i(TAG, "viewDataChanged volume:" + volume);
                soundSB.setProgress(volume);
                setSpeakerState();
                break;
            default:
                break;
        }
    }

    @Override
    public void unRegisterListenService() {
        Log.i(TAG, "unRegisterListenService");
        MeetingManager.getInstance().unregistDataChangeListenerObj(this);
    }

    @Override
    public void registerListenerService() {
        Log.i(TAG, "registerListenerService");
        MeetingManager.getInstance().registerObserved(ObserverConts.SPEAKER_STATUS_CHANGE_MSG, this);
    }
}
